package com.dg.lecheng.manager.controller;

import com.dg.lecheng.api.user.model.InfoUser;
import com.dg.lecheng.base.core.exception.ApplicationException;
import com.dg.lecheng.base.core.exception.ForbiddenException;
import com.dg.lecheng.base.core.exception.UnAuthorizedException;
import com.dg.lecheng.base.core.model.BaseResult;
import com.dg.lecheng.base.core.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/10/22 0022.
 */
@Api(value = "LoginCtroller" ,description = "登陆Controller")
@Controller
public class LoginCtroller extends BaseController{

    @ApiOperation(value = "登陆接口")
    @RequestMapping(value = "/login" ,method = RequestMethod.POST)
    @ResponseBody
    public Object login(@ApiParam(name = "InfoUser" ,value = "登陆用户") @RequestBody InfoUser user , HttpServletRequest request){
        Map result = new HashMap();
        result.put("sessionId",request.getSession().getId());

        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUserName(),user.getPassword());
        try{
            //4.登录，即身份验证
            subject.login(usernamePasswordToken);
        }catch (LockedAccountException e){
            //身份验证失败
            throw new ForbiddenException("账号已锁定");
        }catch (DisabledAccountException lo){
            throw new ForbiddenException("账号已锁定");
        }catch (UnknownAccountException exception){
            throw new UnAuthorizedException("用户名密码错误");
        }catch (IncorrectCredentialsException  e){
            throw new UnAuthorizedException("用户名密码错误");
        }catch (Exception e){
            e.printStackTrace();
            throw new ApplicationException("登陆失败");
        }
        return BaseResult.success(result);
    }
}
